package wre.logic;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Map.Entry;

import wre.Retort;
import wre.Word;
import wre.data.RetortDAO;
import wre.data.WordDAO;

public class RetortManager {
	InputParser inputParser = InputParser.getInstance();
	UpdateManager updateManager;
	RetortDAO retortDAO = RetortDAO.getInstance();
	WordDAO wordDAO = WordDAO.getInstance();

	public String doRetort(String input) {
		List<String> inputWords = inputParser.parseInput(input);
		Map<String, Word> words = wordDAO.getWords();
		Map<Integer, Integer> matches = new HashMap<Integer, Integer>();

		for (String inputWord : inputWords) {
			if (words.containsKey(inputWord)) {
				Integer id = words.get(inputWord).getId();
				if (matches.containsKey(id)) {
					matches.put(id, matches.get(id) + 1);
				} else {
					matches.put(id, 1);
				}
			}
		}

		return getMatch(matches);
	}

	public static void main(String[] args) {
		RetortManager retortManager = new RetortManager();
		System.out.print("Enter a phrase: ");
		Scanner scanner = new Scanner(System.in);
		String input = scanner.nextLine();
		System.out.println(retortManager.doRetort(input));
	}

	private String getMatch(Map<Integer, Integer> matches) {
		Iterator<Entry<Integer, Integer>> iterator = matches.entrySet()
				.iterator();
		Entry<Integer, Integer> entry = null;
		Entry<Integer, Integer> maxEntry = null;
		while (iterator.hasNext()) {
			entry = iterator.next();
			if ((maxEntry == null) || (maxEntry.getValue() < entry.getValue())) {
				maxEntry = entry;
			}
		}
		if (null == maxEntry) {
			return retortDAO.getRetort(1226925925);
		}
		return retortDAO.getRetort(maxEntry.getKey());

	}
}
